/*
 * @Descripttion: 工具集
 * @version: 1.2
 * @LastEditors: sakuya
 * @LastEditTime: 2022年5月24日00:28:56
 */

import CryptoJS from 'crypto-js';
import sysConfig from "@/config";

const tool = {}
/* localStorage */
tool.data = {
	set(key, data, datetime = 0) {
		//加密
		if (sysConfig.LS_ENCRYPTION == "AES") {
			data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)
		}
		let cacheValue = {
			content: data,
			datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
		}
		return localStorage.setItem(key, JSON.stringify(cacheValue))
	},
	get(key) {
		try {
			const value = JSON.parse(localStorage.getItem(key))
			if (value) {

				// let value = value;
				// console.log('value', value)

				let nowTime = new Date().getTime()
				if (nowTime > value.datetime && value.datetime != 0) {
					localStorage.removeItem(key)
					return null;
				}
				//解密
				if (sysConfig.LS_ENCRYPTION == "AES") {
					value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))
				}
				return value.content
			}
			return null
		} catch (err) {
			return null
		}
	},
	remove(key) {
		return localStorage.removeItem(key)
	},
	clear() {
		return localStorage.clear()
	}
}

/*sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set);
	},
	get(table) {
		var data = sessionStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return sessionStorage.removeItem(table);
	},
	clear() {
		return sessionStorage.clear();
	}
}

/*cookie*/
tool.cookie = {
	set(name, value, config = {}) {
		var cfg = {
			expires: null,
			path: null,
			domain: null,
			secure: false,
			httpOnly: false,
			...config
		}
		var cookieStr = `${name}=${escape(value)}`
		if (cfg.expires) {
			var exp = new Date()
			exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000)
			cookieStr += `;expires=${exp.toGMTString()}`
		}
		if (cfg.path) {
			cookieStr += `;path=${cfg.path}`
		}
		if (cfg.domain) {
			cookieStr += `;domain=${cfg.domain}`
		}
		document.cookie = cookieStr
	},
	get(name) {
		var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"))
		if (arr != null) {
			return unescape(arr[2])
		} else {
			return null
		}
	},
	remove(name) {
		var exp = new Date()
		exp.setTime(exp.getTime() - 1)
		document.cookie = `${name}=;expires=${exp.toGMTString()}`
	}
}

/* Fullscreen */
tool.screen = function (element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	if (isFull) {
		if (document.exitFullscreen) {
			document.exitFullscreen();
		} else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		} else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		} else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		}
	} else {
		if (element.requestFullscreen) {
			element.requestFullscreen();
		} else if (element.msRequestFullscreen) {
			element.msRequestFullscreen();
		} else if (element.mozRequestFullScreen) {
			element.mozRequestFullScreen();
		} else if (element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen();
		}
	}
}

/* 复制对象 */
tool.objCopy = function (obj) {
	return JSON.parse(JSON.stringify(obj));
}

/* 日期格式化 */
tool.dateFormat = function (date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	date = new Date(date)
	var o = {
		"M+": date.getMonth() + 1,                 //月份
		"d+": date.getDate(),                    //日
		"h+": date.getHours(),                   //小时
		"m+": date.getMinutes(),                 //分
		"s+": date.getSeconds(),                 //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds()             //毫秒
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
}

/* 千分符 */
tool.groupSeparator = function (num) {
	num = num + '';
	if (!num.includes('.')) {
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
		return $1 + ',';
	}).replace(/\.$/, '');
}

/* 常用加解密 */
tool.crypto = {
	//MD5加密
	MD5(data) {
		return CryptoJS.MD5(data).toString()
	},
	//BASE64加解密
	BASE64: {
		encrypt(data) {
			return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
		},
		decrypt(cipher) {
			return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
		}
	},
	//AES加解密
	AES: {
		encrypt(plainText, keyInBase64Str, config = {}) {
			let key = CryptoJS.enc.Base64.parse(keyInBase64Str);
			let encrypted = CryptoJS.AES.encrypt(plainText, key, {
				// iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode.ECB,
				padding: CryptoJS.pad.Pkcs7,
			});
			// 这里的encrypted不是字符串，而是一个CipherParams对象
			return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
		},
		decrypt(cipherText, keyInBase64Str, config = {}) {
			let key = CryptoJS.enc.Base64.parse(keyInBase64Str);
			// 返回的是一个Word Array Object，其实就是Java里的字节数组
			let decrypted = CryptoJS.AES.decrypt(cipherText, key, {
				// iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode.ECB,
				padding: CryptoJS.pad.Pkcs7,
			});

			return decrypted.toString(CryptoJS.enc.Utf8);
		}
	}
}
tool.random = {
	getRandomId() {
		return `ts_${new Date().getTime().toString().substring(5)}${Math.round(
			Math.random() * 9000 + 1000
		)}`;
	}
}
tool.loadJS = function (src) {
	return new Promise((resolve, reject) => {
		let script = document.createElement('script');
		script.type = "text/javascript";
		script.src = src;
		document.body.appendChild(script);
		script.onload = () => {
			resolve();
		}
		script.onerror = () => {
			reject();
		}
	})
}
//动态添加路由跳转
tool.addHiddenRouter = function (item,data,router){
	let menu = tool.data.get("MENU");
	let exist = false;
	const name = item.path ?  item.path.replace(/\//g, ''): item.url.split("/").map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)).join("");
	if (router.hasRoute(name)) { exist = true }
	if (exist == false) {
	  let route = {
		component: item.url.slice(1),
		name: name,
		path: item.path ? item.path : item.url,
		meta: {
		  affix: false,
		  fullpage: false,
		  hidden: true,
		  icon: "el-icon-add-location",
		  title: item.title,
		  type: "menu",
		},
		children:null,
		redirect: undefined
	  };
	  menu[menu.length - 1].children.push(route);
	  tool.data.set("MENU", menu);
	  route.component = loadComponent(route.component);
	  route.meta.breadcrumb = []
	  route.meta.breadcrumb.push(route)
	  router.addRoute('layout', route);
	  router.push({
		path: item.path ? item.path : item.url,
		query: data,
	  });
	} else {
	  router.push({
		path: item.path ? item.path : item.url,
		query: data,
	  });
	}
}
function loadComponent(component) {
	if (component) {
	  let cpn = () => import(/* webpackChunkName: "[request]" */ `@/views/${component}`)
	  return cpn
	}
	else {
	  return () => import(`@/layout/other/empty`)
	}
  
  }
//四舍五入
tool.formatRoundNum = (num, pre) => {
	let data;
	data = Math.round(num * Math.pow(10, pre)) / Math.pow(10, pre).toFixed(pre)
	return Number(data)
};
//map 转 arr
tool.convert = {
    arrToMap(data){
        let map = {}
        data.forEach(ele => {
            map[ele.key] = ele.value
        });
        return map
    },
    mapToArr(data){
        let arr = []
        for(var key in data){
            const temp = {key:key,value:data[key]}
            arr.push(temp)
        }
        return arr
    }
}
/**
 * 限制new Function函数的作用域
 * @param  {Object} sandbox [作用域
 * @param  {String} code [函数内容]
 */
tool.evalute = (code, sandbox) => {
	sandbox = sandbox || Object.create(null);
	const fn = new Function("sandbox", `with(sandbox){return (${code})}`);
	const proxy = new Proxy(sandbox, {
	  has(target, key) {
		return true;
	  },
	});
	return fn(proxy);
  };




export default tool
